const db = require('../model')
const Rxreq = db.rxreq
const multiparty = require('multiparty')
const fs = require('fs')
const path = require('path')

// 新增处方药申请
exports.createOne = async (req, res) => {
	//生成multiparty对象，并配置上传目标路径
	// 解析一个文件上传
	const PATH = path.join(__dirname, '../upload/images/')
	var form = new multiparty.Form({ uploadDir: PATH })
	// 设置编译
	form.encoding = 'utf-8'
	// 设置单文件大小限制
	form.maxFilesSize = 1 * 1024 * 1024
	// 获取用户的 userId
	const userId = req.session.userId //
	form.parse(req, function (err, fields, files) {
		// 获取传来的 medName
		const { medName } = fields
		// 同步重命名文件名
		for (let file of files.img) {
			const newPath = path.join(
				__dirname,
				`../upload/images/${userId}-${medName}-${file.originalFilename}`
			)

			const oldPath = file.path
			fs.rename(oldPath, newPath, (err) => {
				if (err) {
					console.log(err)
				}
			})
		}

		if (err) {
			console.log(err)
		} else {
			return res.send({
				code: 1,
			})
		}
	})
}
